import type { Question, ExamChannel } from '@/types/exam';
import { questionsMap } from '@/data/exam';
import { examChannels } from '@/data/exam/channels';
import { categories } from '@/data/knowledge';

/**
 * 根据技术ID获取题目列表
 */
export function getQuestionsByTechId(techId: string): Question[] {
	return questionsMap[techId] || [];
}

/**
 * Fisher-Yates洗牌算法 - 确保真正的随机性
 */
function shuffleArray<T>(array: T[]): T[] {
	const shuffled = [...array];
	for (let i = shuffled.length - 1; i > 0; i--) {
		const j = Math.floor(Math.random() * (i + 1));
		[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
	}
	return shuffled;
}

/**
 * 根据分类ID列表获取题目（每次测试10道题，公平随机分配）
 * 策略：
 * 1. 从所有选中分类的题目池中收集所有可用题目
 * 2. 使用Fisher-Yates洗牌算法确保真正的随机性
 * 3. 从打乱后的题目中取前10道，确保每道题都有机会被选中
 */
export function getQuestionsByCategories(techId: string, categoryIds: string[]): Question[] {
	const allQuestions = getQuestionsByTechId(techId);
	const availableQuestions: Question[] = [];
	
	// 收集所有选中分类的题目
	categoryIds.forEach(categoryId => {
		const category = categories.find(c => c.id === categoryId);
		if (!category) return;
		
		// 筛选该分类的所有题目
		const categoryQuestions = allQuestions.filter(q => q.category === category.name);
		availableQuestions.push(...categoryQuestions);
	});
	
	// 如果可用题目少于10道，返回所有题目
	if (availableQuestions.length <= 10) {
		return shuffleArray(availableQuestions);
	}
	
	// 使用Fisher-Yates洗牌算法打乱题目顺序
	const shuffledQuestions = shuffleArray(availableQuestions);
	
	// 返回前10道题
	return shuffledQuestions.slice(0, 10);
}

/**
 * 随机获取指定数量的题目
 */
export function getRandomQuestions(techId: string, count: number): Question[] {
	const allQuestions = getQuestionsByTechId(techId);
	if (allQuestions.length === 0) return [];
	
	// 洗牌算法
	const shuffled = [...allQuestions].sort(() => Math.random() - 0.5);
	return shuffled.slice(0, Math.min(count, shuffled.length));
}

/**
 * 根据技术ID获取测试通道
 */
export function getExamChannelByTechId(techId: string): ExamChannel | undefined {
	return examChannels.find(channel => channel.techId === techId);
}

/**
 * 获取可用的测试通道
 */
export function getAvailableExamChannels(): ExamChannel[] {
	return examChannels.filter(channel => channel.isAvailable);
}

/**
 * 获取所有测试通道
 */
export function getAllExamChannels(): ExamChannel[] {
	return examChannels;
}

